<template>
  <a-modal
    :visible="visible"
    :title="$t('批量导入充电桩')"
    @cancel="handleCancel"
    @before-ok="handleSubmit"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
    >
      <a-form-item field="chargingGroupId" label="所属站点">
        <charging-form
          ref="chargingFormRef"
          :charging-group-id="props.chargingGroupId"
        />
      </a-form-item>
      <a-form-item field="file" label="导入文件" required>
        <a-space direction="vertical" :size="8" fill>
          <a-space>
            <a-upload
              accept=".xls,.xlsx"
              :show-file-list="true"
              :limit="1"
              :auto-upload="false"
              @change="handleFileChange"
            >
              <template #upload-button>
                <a-button>选择文件</a-button>
              </template>
            </a-upload>
            <a-button type="outline" @click="downloadTemplate">下载模板</a-button>
          </a-space>
          <div class="upload-tip">
            支持.xls,.xlsx格式，请确保文件包含：设备编号、充电桩名称、插座数量
          </div>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { FileItem } from '@arco-design/web-vue';
import * as XLSX from 'xlsx';
import { importChargingPiles } from '@/api/charging';
import ChargingForm from './charging-form.vue';

const props = defineProps<{
  visible: boolean;
  chargingGroupId?: number | null;
  groupName?: string;
}>();

const emit = defineEmits(['update:visible', 'success']);

// 加载状态
const loading = ref(false);

// 表单引用
const formRef = ref();
const chargingFormRef = ref();

// 表单数据
const form = reactive({
  file: null as File | null,
});

// 表单校验规则
const rules = {
  file: [
    { required: true, message: '请选择文件' }
  ]
};

// 处理文件变化
const handleFileChange = (files: FileItem[]) => {
  if (files.length > 0 && files[0].file) {
    form.file = files[0].file;
  } else {
    form.file = null;
  }
};

// 处理取消
const handleCancel = () => {
  emit('update:visible', false);
  form.file = null;
  chargingFormRef.value?.resetForm();
};

// 处理提交
const handleSubmit = async () => {
  if (!form.file) {
    Message.warning('请选择文件');
    return false;
  }

  // 验证表单
  try {
    await chargingFormRef.value?.validate();
  } catch (error) {
    return false;
  }

  loading.value = true;
  try {
    const workbook = await readExcelFile(form.file);
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const data = XLSX.utils.sheet_to_json(sheet) as any[];
    
    if (!data || data.length === 0) {
      Message.error('Excel文件内容为空');
      return false;
    }

    // 验证数据格式
    const isValid = data.every(row => {
      return row['设备编号'] && row['充电桩名称'] && row['插座数量'];
    });

    if (!isValid) {
      Message.error('Excel文件格式不正确，请确保包含：设备编号、充电桩名称、插座数量');
      return false;
    }

    const formData = chargingFormRef.value?.getFormData();
    
    // 转换数据格式
    const importData = data.map(row => ({
      code: row['设备编号'],
      name: row['充电桩名称'],
      socketCount: Number(row['插座数量']),
      chargingGroupId: formData.chargingGroupId
    }));

    // 调用导入API
    const res = await importChargingPiles(importData);
    if (res.code === 200) {
      Message.success('导入成功');
      emit('success');
      handleCancel();
    } else {
      Message.error(res.message || '导入失败');
    }
  } catch (error: any) {
    console.error('处理Excel文件失败:', error);
    Message.error(error.message || '处理Excel文件失败');
    return false;
  } finally {
    loading.value = false;
  }
};

// 读取Excel文件
const readExcelFile = (file: File): Promise<XLSX.WorkBook> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target?.result as ArrayBuffer);
        const workbook = XLSX.read(data, { type: 'array' });
        resolve(workbook);
      } catch (error) {
        reject(error);
      }
    };
    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);
  });
};

// 下载模板
const downloadTemplate = () => {
  // 创建工作簿
  const wb = XLSX.utils.book_new();
  
  // 示例数据
  const exampleData = [
    {
      '设备编号': 'PILE2024001',
      '充电桩名称': '1号充电桩',
      '插座数量': 2
    },
    {
      '设备编号': 'PILE2024002',
      '充电桩名称': '2号充电桩',
      '插座数量': 4
    }
  ];

  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(exampleData);
  
  // 设置列宽
  const colWidth = [
    { wch: 15 }, // 设备编号
    { wch: 15 }, // 充电桩名称
    { wch: 10 }, // 插座数量
  ];
  ws['!cols'] = colWidth;

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '充电桩导入模板');

  // 下载文件
  XLSX.writeFile(wb, '充电桩导入模板.xlsx');
};
</script>

<style scoped>
.upload-tip {
  color: #999;
  font-size: 12px;
  line-height: 1.5;
}
</style> 